package com.siss.tenancy.user.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.Map;

/**
 * @author 李宜朋
 * @ClassName FreemarkerUtil
 * @Description 模板引擎工具类
 * @date 2020/9/8 15:53
 * @Version 2.0
 */

public class FreemarkerUtil {


    public static File generalDoc(String templateFileName,String templateFilePath,String outPath,Map<String,Object> dataModel) throws Exception {
        Configuration  freeMarkerConfigurer = new Configuration();
        Template template = null;
        Writer out = null;
        File file = ResourceUtils.getFile(outPath);
        if(!file.exists()){
           file.createNewFile();
        }
        try {
            // 输出文件
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            InputStream inputStream = new FileInputStream(new File(templateFilePath));
            String templateStr = null;
            try {
                templateStr = IOUtils.toString(inputStream);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                template = new Template(templateFileName,new StringReader(templateStr), freeMarkerConfigurer);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            template.process(dataModel, out);
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭流
            IOUtils.closeQuietly(out);
        }
        return file;
    }

    public static ByteArrayOutputStream getByteArrayOutputStreamByFile(File file)throws Exception{
        FileInputStream  fis = new FileInputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int iLength = 0;
        while((iLength = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, iLength);
        }
        fis.close();
        baos.close();
        return baos;
    }

/*    public static void main(String[] args) throws Exception{
        String templateFilePath = "D:\\work\\wzm_workSpace\\organApplyInfoless.ftl";
        String outPath = "D:\\work\\wzm_workSpace\\organApplyInfo0"+ParserDate.getFDay(new Date(),"yyyyMMddHHmmss")+".doc";
        File docFile = generalDoc("organApplyInfoless.ftl",templateFilePath,outPath,null);
        Document document = new Document();
        document.loadFromFile(outPath);
        document.saveToFile("D:\\work\\wzm_workSpace\\organApplyInfo1"+ParserDate.getFDay(new Date(),"yyyyMMddHHmmss")+".pdf", FileFormat.PDF);
    }*/
}
